package com.goalias.interceptor;


import cn.hutool.json.JSONUtil;
import com.goalias.constant.RedisConstants;
import com.goalias.feign.domain.UserInfo;
import com.goalias.service.RedisService;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Component
public class UserInterceptor implements HandlerInterceptor {

    @Resource
    private RedisService redisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String userId = request.getHeader("userId");

        String userInfoJson = (String) redisService.get(RedisConstants.USERINFO+userId);
        if (!StringUtils.hasText(userInfoJson)){
            return true;
        }
        UserInfo userInfo = JSONUtil.toBean(userInfoJson, UserInfo.class);
        UserInfo.set(userInfo);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserInfo.remove();
    }
}
